package com.fht.controller.inventory;


import com.fht.constant.ManagermentSystemConstant;
import com.fht.entity.*;
import com.fht.enums.ManagermentSystemEnum;
import com.fht.exception.ManagermentSystemException;
import com.fht.from.inventoryFrom;
import com.fht.service.food.FoodMaterialCategoryService;
import com.fht.service.food.MerchantsInformationService;
import com.fht.service.inventory.PurchaseOrdersParticularsService;
import com.fht.service.inventory.PurchaseOrdersService;
import com.fht.util.GenerateOrdersIDUtil;
import com.fht.util.ResultVOUtil;
import com.fht.util.UnitConversionUtil;
import com.fht.vo.LayUITableVO;
import com.fht.vo.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.lang.reflect.InvocationTargetException;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@Slf4j
@RequestMapping("/purchase/orders")
public class PurchaseOrdersController {


    @Autowired
    public PurchaseOrdersService purchaseOrdersService;

    @Autowired
    public MerchantsInformationService merchantsInformationService;

    @Autowired
    public FoodMaterialCategoryService foodMaterialCategoryService;

    @Autowired
    public PurchaseOrdersParticularsService purchaseOrdersParticularsService;

    //菜品类别展示
    @GetMapping("/index")
    public String index(Model model){

        List<MerchantsInformation> merchantsInformationList = merchantsInformationService.findAllIdAndName();
        model.addAttribute("merchantsInformationList",merchantsInformationList);

        return "inventory/purchaseOrders/index";

    }
    //获取菜品类别信息
    @GetMapping("/list")
    @ResponseBody
    public LayUITableVO<List<PurchaseOrders>> list (@RequestParam(defaultValue = "1") Integer page,
                                                @RequestParam(defaultValue = "10") Integer limit,
                                                    inventoryFrom from){
        Map<String ,Object> map = new HashMap<>();
        map.put("page",page);
        map.put("limit",limit);
        map.put("from",from);

        LayUITableVO<List<PurchaseOrders>> vo = purchaseOrdersService.findPage(map);


        return vo;
    }

    //跳转到修改页面
    @GetMapping("/edit-ui")
    public String editUI(String id,Model model){

        PurchaseOrders purchaseOrders = purchaseOrdersService.selectById(id);

        List<MerchantsInformation> merchantsInformationList = merchantsInformationService.findAllIdAndName();
        model.addAttribute("merchantsInformationList",merchantsInformationList);
        model.addAttribute("purchaseOrders",purchaseOrders);

        return "inventory/purchaseOrders/edit";

    }
    //查询订单详情信息，并放入map缓存中
    @GetMapping("/ordersList")
    @ResponseBody
    public LayUITableVO<List<PurchaseOrdersParticulars>> ordersList (@RequestParam(defaultValue = "1") Integer page,
                                                                    @RequestParam(defaultValue = "10") Integer limit,
                                                                    String id){

        LayUITableVO<List<PurchaseOrdersParticulars>> vo = purchaseOrdersParticularsService.findPageById(id);

        ManagermentSystemConstant.PURCHASE_ORDERS_PARTICULARS_MAP.put(id,vo);

        return vo;
    }

    //修改map缓存中的数据，并重新计算价格总和
    @PostMapping("/editMap")
    @ResponseBody
    public ResultVO editMap (PurchaseOrdersParticulars purchaseOrdersParticulars){


        LayUITableVO<List<PurchaseOrdersParticulars>> listLayUITableVO = ManagermentSystemConstant.PURCHASE_ORDERS_PARTICULARS_MAP.get(purchaseOrdersParticulars.getId());
        List<PurchaseOrdersParticulars> dataList = listLayUITableVO.getData();

        for (PurchaseOrdersParticulars data : dataList) {
            if (data.getMaterialId().equals(purchaseOrdersParticulars.getMaterialId())){

                data.setPurchaseNum(purchaseOrdersParticulars.getPurchaseNum());
                data.setSubtotalString(UnitConversionUtil.conversion(UnitConversionUtil.conversion(purchaseOrdersParticulars.getUnitPrice())*purchaseOrdersParticulars.getPurchaseNum()));
                data.setRemark(purchaseOrdersParticulars.getRemark());
            }
        }

        return ResultVOUtil.ok();
    }

    //刷新订单详情信息，将修改好的新的价格总和给页面
    @GetMapping("/refresh")
    @ResponseBody
    public LayUITableVO<List<PurchaseOrdersParticulars>> refresh (@RequestParam(defaultValue = "1") Integer page,
                                                                     @RequestParam(defaultValue = "10") Integer limit,
                                                                     String id){


        return ManagermentSystemConstant.PURCHASE_ORDERS_PARTICULARS_MAP.get(id);
    }

    //删除map缓存中的指定的一条详情信息
    @PostMapping("/delMap")
    @ResponseBody
    public ResultVO delMap (String id,String materialId){


        LayUITableVO<List<PurchaseOrdersParticulars>> listLayUITableVO = ManagermentSystemConstant.PURCHASE_ORDERS_PARTICULARS_MAP.get(id);
        List<PurchaseOrdersParticulars> dataList = listLayUITableVO.getData();

        for (PurchaseOrdersParticulars data : dataList) {
            if (String.valueOf(data.getMaterialId()).equals(materialId)){

                dataList.remove(data);
                break;
            }
        }

        purchaseOrdersParticularsService.deleteByIdAndMaterialId(id,materialId);
        return ResultVOUtil.ok();
    }

    //选择菜品原料页面
    @GetMapping("/edit-chooseMaterial-ui")
    public String editChooseMaterialUI(String merchantsId,String orderId,Model model){


        List<FoodMaterialCategory> foodMaterialCategories = foodMaterialCategoryService.selectBymerchantsId(merchantsId);
        model.addAttribute("foodMaterialCategories",foodMaterialCategories);
        model.addAttribute("merchantsId",merchantsId);
        model.addAttribute("orderId",orderId);

        return "inventory/purchaseOrders/chooseMaterial";

    }

    //将选中的菜品原料信息放入到map缓存中
    @PostMapping("/addMap")
    @ResponseBody
    public ResultVO addMap ( @RequestBody Map<String,Object> map){





        List<Map<String,String>> foodMaterialManagerList = (List<Map<String,String>>) map.get("data");
        String orderId = (String) map.get("orderId");

        LayUITableVO<List<PurchaseOrdersParticulars>> listLayUITableVO = ManagermentSystemConstant.PURCHASE_ORDERS_PARTICULARS_MAP.get(orderId);
        List<PurchaseOrdersParticulars> dataList = listLayUITableVO.getData();

        List<Integer> materialIdList = new ArrayList<>();
        for (PurchaseOrdersParticulars purchaseOrdersParticulars : dataList) {

            materialIdList.add(purchaseOrdersParticulars.getMaterialId());
        }

        for (Map<String,String> map1 : foodMaterialManagerList) {


            PurchaseOrdersParticulars purchaseOrdersParticulars = new PurchaseOrdersParticulars();
            try {
                BeanUtils.populate(purchaseOrdersParticulars,map1);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
            if (materialIdList.size() !=0 && materialIdList.contains(Integer.valueOf(purchaseOrdersParticulars.getId() ))){

                continue;
            }
            purchaseOrdersParticulars.setPurchaseUnit(map1.get("purchaseUnitName"));
            purchaseOrdersParticulars.setRepertoryUnit(map1.get("repertoryUnitName"));
            purchaseOrdersParticulars.setPurchaseNum(0);
            purchaseOrdersParticulars.setSubtotal(0);
            purchaseOrdersParticulars.setSubtotalString("0");
            purchaseOrdersParticulars.setMaterialId(Integer.valueOf(purchaseOrdersParticulars.getId()));
            purchaseOrdersParticulars.setId(orderId);
            purchaseOrdersParticulars.setUnitPrice(UnitConversionUtil.conversion(Integer.valueOf(purchaseOrdersParticulars.getUnitPrice())));
            dataList.add(purchaseOrdersParticulars);
        }

        return ResultVOUtil.ok();
    }


    //取消操作，删除map中的缓存
    @PostMapping("/delAllMap")
    @ResponseBody
    public ResultVO delAllMap (String id){


        Set<String> keySet = ManagermentSystemConstant.PURCHASE_ORDERS_PARTICULARS_MAP.keySet();
        for (String s : keySet) {
            if (s.equals(id)){
                ManagermentSystemConstant.PURCHASE_ORDERS_PARTICULARS_MAP.remove(id);
            }
        }


        return ResultVOUtil.ok();
    }


    //提交操作（修改或添加），判断订单详情的数据完整性，分别存入两表中，移除map缓存
    @PostMapping("/saveMap")
    @ResponseBody
    public ResultVO saveMap (PurchaseOrders purchaseOrders){

        LayUITableVO<List<PurchaseOrdersParticulars>> listLayUITableVO = ManagermentSystemConstant.PURCHASE_ORDERS_PARTICULARS_MAP.get(purchaseOrders.getId());

        List<PurchaseOrdersParticulars> dataList = listLayUITableVO.getData();
        if (dataList.size()==0){
            throw new ManagermentSystemException(ManagermentSystemEnum.PARM_INCOMPLETE);
        }

        Integer total = 0;
        for (PurchaseOrdersParticulars purchaseOrdersParticulars : dataList) {

            if (purchaseOrdersParticulars.getPurchaseNum()==0){
                throw new ManagermentSystemException(ManagermentSystemEnum.PARM_INCOMPLETE);
            }
            total += UnitConversionUtil.conversion(purchaseOrdersParticulars.getSubtotalString());

        }

        purchaseOrders.setTotal(total);
        purchaseOrdersService.update(purchaseOrders);

        purchaseOrdersParticularsService.save(dataList);


        Set<String> keySet = ManagermentSystemConstant.PURCHASE_ORDERS_PARTICULARS_MAP.keySet();
        for (String s : keySet) {
            if (s.equals(purchaseOrders.getId())){
                ManagermentSystemConstant.PURCHASE_ORDERS_PARTICULARS_MAP.remove(purchaseOrders.getId());
            }
        }


        return ResultVOUtil.ok();
    }

    //跳转到添加页面
    @GetMapping("/add-ui")
    public String addUI(String merchantsId,Model model){

        PurchaseOrders purchaseOrders = new PurchaseOrders();

        purchaseOrders.setId("PO"+GenerateOrdersIDUtil.generateOrdersID(1001));
        purchaseOrders.setMerchantsId(Integer.valueOf(merchantsId));
        purchaseOrders.setStatusString("未审核");
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        String time =  df.format(new Date());// new Date()为获取当前系统时间
        purchaseOrders.setPreparedBy("小红");
        purchaseOrders.setPreparedDate(time);

        List<MerchantsInformation> merchantsInformationList = merchantsInformationService.findAllIdAndName();
        model.addAttribute("merchantsInformationList",merchantsInformationList);

        model.addAttribute("purchaseOrders",purchaseOrders);

        return "inventory/purchaseOrders/add";

    }


    //跳转到审核页面
    @GetMapping("/audit-ui")
    public String auditUI(String id,Model model){

        PurchaseOrders purchaseOrders = purchaseOrdersService.selectById(id);


        List<MerchantsInformation> merchantsInformationList = merchantsInformationService.findAllIdAndName();
        model.addAttribute("merchantsInformationList",merchantsInformationList);
        model.addAttribute("purchaseOrders",purchaseOrders);

        return "inventory/purchaseOrders/audit";

    }

    //跳转到审核提交页面
    @GetMapping("/auditStatus-ui")
    public String auditStatusUI(String id,Model model){


        model.addAttribute("id",id);

        return "inventory/purchaseOrders/auditStatus";

    }




    //修改审核状态
    @PostMapping("/updateState")
    @ResponseBody
    public ResultVO updateState (PurchaseOrders purchaseOrders){
        //TODO 登录用户名
        purchaseOrders.setVerifier("小绿");
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        String time =  df.format(new Date());// new Date()为获取当前系统时间
        purchaseOrders.setVerifierDate(time);
        purchaseOrdersService.update(purchaseOrders);

        return ResultVOUtil.ok(purchaseOrders);
    }


    //跳转到查看页面
    @GetMapping("/show-ui")
    public String showUI(String id,Model model){

        PurchaseOrders purchaseOrders = purchaseOrdersService.selectById(id);

        List<MerchantsInformation> merchantsInformationList = merchantsInformationService.findAllIdAndName();
        model.addAttribute("merchantsInformationList",merchantsInformationList);
        model.addAttribute("purchaseOrders",purchaseOrders);

        return "inventory/purchaseOrders/show";

    }



    //删除
    @PostMapping("/del")
    @ResponseBody
    public ResultVO del (String id){

        purchaseOrdersService.deleteById(id);

        purchaseOrdersParticularsService.deleteById(id);


        return ResultVOUtil.ok();
    }






}
